import { ref } from 'vue';
import { useUserStore } from '@/stores/user.js';
import { ElMessage } from 'element-plus';
import {getUserByUsername} from "@/api/user.js";

export const useUser = () => {
    const user = ref({
        id: 'user123',
        username: 'Raise(fake)',
        avatar: 'https://img.tukuppt.com/png_preview/00/52/31/gqsUON6GeI.jpg!/fw/780',
        // level: 42,
        // currentExp: 1250,
        // nextLevelExp: 1500,
        // expProgress: 83.3,
        playCount: 156,
        winRate: 68.5,
        isOnline: true
    });

    const getUserProfile = async () => {

        try {
            const username = useUserStore().username;
            if (!username) {
                throw new Error('空用户');
            }

            const userData = await getUserByUsername(username);
            console.log('获取到的用户数据:', userData);

            // 更新响应式user对象
            user.value = {
                ...userData,
                avatar: 'https://img.tukuppt.com/png_preview/00/52/31/gqsUON6GeI.jpg!/fw/780',
                isOnline: true // 根据需要设置
            };

            // 更新store
            useUserStore().setUser(user.value);

            return user.value;
        } catch (err) {
            error.value = err;
            ElMessage.error('获取用户信息失败: ' + err.message);
            throw err;
        }
    };

    return { user, getUserProfile };
};